<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small"
                        prefix-icon="el-icon-search" style="margin-bottom: 20px"/>
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
                       :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                       @node-click="handleNodeClick"/>
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <div ref="formRef">
              <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                       label-width="68px">
                <el-form-item label="医生姓名" prop="doctorName">
                  <el-input
                    v-model="queryParams.doctorName"
                    placeholder="请输入医生姓名"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="患者姓名" prop="patientName">
                  <el-input
                    v-model="queryParams.patientName"
                    placeholder="请输入医生姓名"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>

                <el-form-item label="画课月份">
                  <el-date-picker v-model="courseMonth" style="width: 120px" placeholder="选择月份" type="month" ></el-date-picker>
                </el-form-item>

                <el-form-item label="画课日期">
                  <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                                  range-separator="-" start-placeholder="开始日期"
                                  end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
              </el-form>
            </div>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['yushi:course:export']"
                >导出
                </el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
              <el-col :span="1.5" class="top-right-btn">
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-col>
              <el-col :span="1.5" class="top-right-btn">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              </el-col>
            </el-row>
            <el-table v-loading="loading" :data="tableData" :height="tableHeight"
                      :summary-method="getSummaries"
                      show-summary
                      ref="summaryTable"
                      @selection-change="handleSelectionChange" >
              <el-table-column type="selection" width="60" align="center"/>
              <el-table-column label="序号" type="index" align="center" width="60">
                <template slot-scope="scope">
                  <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="医生姓名" align="center" prop="doctorName" width="120"/>
              <el-table-column label="患者姓名" align="center" prop="patientName" width="120"/>
              <el-table-column label="院区名称" align="center" prop="parentName" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.dept.parentName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="科室名称" align="center" prop="deptName" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.dept.deptName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="画课月份" align="center" prop="courseMonth" width="80"/>
              <el-table-column label="当月上课量" align="center" prop="courseHourTMonth" width="120"/>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="goCourse(scope.row)"
                    v-hasPermi="['yushi:doctor:edit']"
                  >查看详情
                  </el-button>

                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
  </div>
</template>

<script>
import {getDoctorCourseStatisticsList} from "@/api/yushi/course";
import {getRoleByRoleKey} from "@/api/system/role";
import {deptTreeSelect} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import {Splitpanes, Pane} from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {parseTime} from "@/utils/ruoyi";

export default {
  name: "DoctorStatistics",
  components: {Treeselect, Splitpanes, Pane},
  dicts: ['sys_user_sex'],
  data() {
    return {
      tableHeight: '',//表格高度
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      pageNum: 1,
      pageSize: 10,
      //查询月份
      courseMonth:'',
      // 日期范围
      dateRange: [],
      doctorRoleKey: "doctor",
      doctorRoleId: "",
      // 医生管理表格数据
      tableData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 查询参数
      // orderByColumn: 'a.create_time',
      // isAsc: 'desc',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        doctorName: null,
        patientName: null,
        sex: null,
        birthday: null,
        phonenumber: null,
        idcardNo: null,
        courseHoursToday: null,
        courseHoursTmonth: null,
        courseHoursLmonth: null,
        deptId: null,
        deptName: null
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {},
      resizeObserver: null,
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getRoleByRoleKey()
    this.getTableHeight()
  },
  mounted() {
    //挂载window.onresize事件(动态设置table高度)
    const _this = this;
    window.onresize = () => {
      if (_this.resizeFlag) {
        clearTimeout(_this.resizeFlag);
      }
      _this.resizeFlag = setTimeout(() => {
        _this.getTableHeight();
        _this.resizeFlag = null;
      }, 100);
    };
    _this.getTableHeight()
    _this.initResizeObserver();
  },
  beforeDestroy() {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
  },
  methods: {
    // 初始化ResizeObserver
    initResizeObserver() {
      if (typeof ResizeObserver !== 'undefined' && this.$refs.tableWrapper) {
        this.resizeObserver = new ResizeObserver(() => {
          this.updateTableLayout();
        });
        this.resizeObserver.observe(this.$refs.tableWrapper);
      }
    },

    // 更新表格布局
    updateTableLayout() {
      if (this.$refs.summaryTable && this.$refs.summaryTable.doLayout) {
        setTimeout(() => {
          this.$refs.summaryTable.doLayout();
        }, 100);
      }
    },
    //计算table高度(动态设置table高度)
    getTableHeight() {
      const that = this
      const innerHeight = window.innerHeight
      const formRefHeight = that.$refs.formRef.offsetHeight
      //距离页面下方的高度
      let tableH = 198 + formRefHeight;
      let tableHeightDetil = innerHeight - tableH;
      if (tableHeightDetil <= 300) {
        that.tableHeight = 300;
      } else {
        that.tableHeight = window.innerHeight - tableH;
      }
    },
    /** 查询医生角色ID */
    getRoleByRoleKey() {
      getRoleByRoleKey(this.doctorRoleKey).then(response => {
        if (response.data != null) {
          this.doctorRoleId = response.data.roleId
          this.getList()
          this.getDeptTree()
        }
      })
    },
    /** 查询医生管理列表 */
    getList() {
      this.loading = true
      let params = this.queryParams
      params.roleId = this.doctorRoleId
      params.courseMonth = this.parseTime(this.courseMonth, '{y}-{m}')
      getDoctorCourseStatisticsList(this.addDateRange(params, this.dateRange)).then(response => {
        this.tableData = response.rows
        this.total = response.total
        this.loading = false
        this.getTableHeight()
      })
    },
    goCourse(row) {
      this.$router.push("/course?doctorName=" + row.doctorName + "&patientName=" + row.patientName + "&courseStatus=2" + "&courseMonth=" + row.courseMonth)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        doctorId: null,
        nickName: null,
        sex: null,
        birthday: null,
        phonenumber: null,
        idcardNo: null,
        courseHoursToday: null,
        courseHoursTmonth: null,
        courseHoursLmonth: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deptId: null,
        deptName: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.courseMonth = ''
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.doctorId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },


    /** 导出按钮操作 */
    handleExport() {
      if(this.courseMonth == null || this.courseMonth == ''){
        this.$modal.msgError("请选择月份!")
        return
      }
      this.queryParams.courseMonth = this.parseTime(this.courseMonth, '{y}-{m}')
      this.download('/yushi/course/exportDoctorPatientStatistics', {
      // this.download('/yushi/course/exportDoctorPatient', {
        ...this.queryParams
      }, this.queryParams.courseMonth+`工作量_${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`)
    },

    // handleExport() {
    //   this.download('/yushi/course/exportDoctorCourseStatistics', {
    //     ...this.queryParams
    //   }, `医生统计_${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`)
    // },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
      })
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    // 合计行计算方法
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const prop = column.property;
        if (prop === 'courseHourTMonth') {
          const values = data.map(item => {
            if (prop === 'total') {
              return item.amount * item.quantity;
            }
            return Number(item[prop]);
          });

          if (!values.every(value => isNaN(value))) {
            const sum = values.reduce((prev, curr) => {
              const value = Number(curr);
              return !isNaN(value) ? prev + value : prev;
            }, 0);

            if (prop === 'amount' || prop === 'total') {
              sums[index] = '¥ ' + sum.toLocaleString();
            } else {
              sums[index] = sum.toLocaleString();
            }
          } else {
            sums[index] = 'N/A';
          }
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
  }
}
</script>
